<template>
  <div>
    <el-card class="box-card">
      <div v-if="commentlist.length">
        <div class="conment" v-for="(item, index) in commentlist" :key="index">
          <el-row>
            <el-col :span="2">
              <div>
                <el-avatar
                  :src="item.header_pic"
                  shape="square"
                  size="medium"
                ></el-avatar>
              </div>
            </el-col>
            <el-col :span="18">
              <p>{{ item.username }}</p>
              <p>{{ item.comment_content }}</p>
            </el-col>
          </el-row>
        </div>
      </div>
      <div v-else style="text-align: center">暂无评论！</div>
    </el-card>

    <el-card>
      <el-input
        v-model="issue_comment.comment_content"
        type="textarea"
        :rows="5"
        placeholder="请输入评论内容..."
      >
      </el-input>

      <el-button type="primary" @click="issueTopic">发布评论</el-button>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 当前点击话题的id
      id: this.$route.params.id,
      // 评论的内容
      commentlist: {},
      // 话题输入框内容
      issue_comment: {
        comment_content: '',
        user_id: JSON.parse(sessionStorage.getItem('user')).user_id,
        topic_id: this.$route.params.id,
        topic_commentNum: ''
      }

    }
  },
  created () {
    this.getClickTopic(this.id)
    this.getComment()
  },
  methods: {
    // 获取评论数量
    async getClickTopic (id) {
      const { data: res } = await this.$http.post('/topic_content', { topicId: id })
      this.issue_comment.topic_commentNum = res.topic_commentNum
    },
    // 获取评论信息
    async getComment () {
      const { data: res } = await this.$http.get('/get_topic_comment?id=' + this.id)
      this.commentlist = res
    },
    // 发布评论
    async issueTopic () {
      const { data: res1 } = await this.$http.put('/issue_comment', this.issue_comment)
      const { data: res2 } = await this.$http.put('/addCommentNum', this.issue_comment)
      if (!res1 && !res2) {
        this.$message.error('评论失败！')
      }
      this.issue_comment.comment_content = ''
      this.$router.push('/topic/' + this.id + '?key=' + Math.random())
      this.$message.success(res1.message)
    }
  }
}
</script>

<style lang="less" scoped>
p {
  margin-top: 10px;
  margin-bottom: 0px;
  line-height: 20px;
}

.conment {
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.el-button {
  margin: 15px 0;
  float: right;
}

.el-avatar {
  border-radius: 50%;
}
</style>
